import { Equals, proxy } from "../utils";
import { LineCmp } from "../utils/lineUtil";
import { dot, perp } from "../utils/math";
import { Point3d } from "./Point3d";
import { Vector2d } from "./Vector2d";
import _ from 'lodash';
import { wallScenes } from "../scenes";
const defaultWidth = 10;
export class Wall{
  constructor(ctx){
    this.data = {
      color: 'red',
      startPt: null,    // 起点
      endPt: null,      // 终点
      length: null,     // 长
      width: defaultWidth,      // 宽
    }
    this.ctx = ctx;
    this.leftUpPt = null; // v0
    this.rightUpPt = null; // v1
    this.rightDownPt = null; // v2
    this.leftDownPt = null; // v3
    this.initState();
  }
  initState() {
    const instance = this;
    Object.keys(this.data).forEach(key => {
      proxy(instance, `_proxy`, key)
    });
  }

  setStartPt(pt){
    this.startPt = pt;
  }
  setEndPt(pt){
    this.endPt = pt;
    this.length = LineCmp.distPt(this.startPt, pt).toFixed(2);
  }
  setCtx(ctx) {
    this.ctx = ctx;
  }
  isIn(pt){
    if(! pt instanceof Point3d) return false;
    // console.log('123');
    // const nPerp = perp(this.leftUpPt, this.rightDownPt);
    // const nMinus = pt.minus(this.leftUpPt);
    // const result = dot(nPerp, nMinus);
    // console.log(result);
    if(dot(perp(this.leftUpPt, this.rightDownPt), pt.minus(this.leftUpPt)) > 0){
      if(dot(perp(this.leftUpPt, this.rightUpPt), pt.minus(this.rightUpPt)) > 0) return false;
      if(dot(perp(this.rightUpPt, this.rightDownPt), pt.minus(this.rightUpPt)) > 0) return false;
    } else {
      if(dot(perp(this.rightDownPt, this.leftDownPt), pt.minus(this.leftDownPt)) > 0) return false;
      if(dot(perp(this.leftDownPt, this.leftUpPt), pt.minus(this.leftDownPt)) > 0) return false;
    }
    return true;
  }
  render(isUp){
    this.ctx.lineWidth = 1;
    this.ctx.strokeStyle = this.color;
    this.ctx.fillStyle = 'goldenrod';
    const vec = new Vector2d(this.startPt, this.endPt);
    this.leftUpPt = this.startPt.plus(vec.n.mul(this.width));
    this.rightUpPt = this.endPt.plus(vec.n.mul(this.width));
    this.leftDownPt = this.startPt.minus(vec.n.mul(this.width));
    this.rightDownPt = this.endPt.minus(vec.n.mul(this.width));
    this.ctx.beginPath();
    this.ctx.moveTo(this.leftUpPt.x, this.leftUpPt.y);
    this.ctx.lineTo(this.rightUpPt.x, this.rightUpPt.y);
    this.ctx.lineTo(this.rightDownPt.x, this.rightDownPt.y);
    this.ctx.lineTo(this.leftDownPt.x, this.leftDownPt.y);
    this.ctx.lineTo(this.leftUpPt.x, this.leftUpPt.y);
    this.ctx.stroke();
    this.ctx.fill();
    // if(guidewires) {
    //   this.drawGuidewires();
    // }
    if (isUp) {
      const newEntity = _.cloneDeep(this);
      wallScenes.push(newEntity);
    }
  }
}